<script setup lang="ts">
import { ref, reactive, h, onMounted, computed } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { PaginationConfig, TableColumn } from "@/components/DynamicTable/types";
import {
  ElMessage,
  ElTag,
  ElButton,
  ElMessageBox,
  ElTooltip,
} from "element-plus";
import {
  getGithubCache,
  confirmGithubCache,
  ignoreGithubCache,
  cleanupGithubCache,
} from "../../servers";
import DynamicForm from "@/components/DynamicForm";
import DynamicStatistics, {
  type StatisticsItem,
} from "@/components/DynamicStatistics";
import ConfirmCacheDialog from "./components/ConfirmCacheDialog.vue";

const props = defineProps<{
  task: string;
}>();

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const cacheList = ref<any[]>([]);
const loading = ref(false);
const formRef = ref<any>(null);
const statistics = ref<StatisticsItem[]>([]);
const selectedRows = ref<any[]>([]);
const showConfirmDialog = ref(false);
const pendingConfirmKeys = ref<string[]>([]);

// 筛选表单数据
const filterForm = reactive({
  task_id: "",
  keyword: "",
});

// 筛选表单配置
const formConfig = [
  {
    key: "task_id",
    name: "任务",
    type: "select" as const,
    defaultValue: "",
    placeholder: "全部任务",
    params: {
      clearable: true,
    },
    options: [
      { label: "全部任务", value: "" },
      // TODO: 从任务列表获取选项
    ],
    labelWidth: "80px",
  },
  {
    key: "keyword",
    name: "搜索",
    type: "input" as const,
    defaultValue: "",
    placeholder: "请输入关键词（仓库、文件路径等）",
    params: {
      clearable: true,
    },
    col: {
      span: 6,
    },
  },
];

// 格式化TTL显示
const formatTTL = (ttlHours: number) => {
  if (!ttlHours && ttlHours !== 0) return "-";
  if (ttlHours < 1) {
    return `${Math.round(ttlHours * 60)} 分钟`;
  }
  return `${ttlHours.toFixed(1)} 小时`;
};

// 获取TTL进度条百分比
const getTTLProgress = (ttlHours: number, maxHours: number = 24) => {
  if (!ttlHours && ttlHours !== 0) return 0;
  return Math.min(Math.round((ttlHours / maxHours) * 100), 100);
};

// 获取评分颜色
const getScoreColor = (score: number) => {
  if (score >= 80) return "#f56c6c"; // 红色 - 高风险
  if (score >= 60) return "#e6a23c"; // 橙色 - 中风险
  return "#67c23a"; // 绿色 - 低风险
};

const historyColumns = ref<TableColumn[]>([
  {
    label: "仓库",
    prop: "repository",
    minWidth: 250,
    show: true,
    render: (row) => {
      const repo = row.repository || {};
      return h(
        "div",
        { style: "display: flex; flex-direction: column; gap: 4px" },
        [
          h("div", { style: "display: flex; align-items: center; gap: 8px" }, [
            h(
              "a",
              {
                href: repo.html_url,
                target: "_blank",
                style: {
                  color: "#409eff",
                  textDecoration: "underline",
                  fontWeight: "500",
                },
              },
              repo.name || "-"
            ),
            row.source === "github" || row.source === "manual_test"
              ? h(ElTag, { type: "info", size: "small" }, () =>
                  row.source === "github" ? "GitHub" : "手动测试"
                )
              : null,
          ]),
          repo.description
            ? h(
                "div",
                { style: "font-size: 12px; color: #909399" },
                repo.description
              )
            : null,
        ]
      );
    },
  },
  {
    label: "文件路径",
    prop: "path",
    minWidth: 200,
    show: true,
    render: (row) => {
      const fileName = row.path?.split("/").pop() || row.path || "-";
      return h("div", [
        h(
          "a",
          {
            href: row.html_url,
            target: "_blank",
            style: {
              color: "#409eff",
              textDecoration: "underline",
              fontWeight: "500",
            },
          },
          fileName
        ),
        h(
          "div",
          { style: "font-size: 12px; color: #909399; margin-top: 4px" },
          row.path || "-"
        ),
      ]);
    },
  },
  {
    label: "匹配部门",
    prop: "matched_departments",
    width: 150,
    show: true,
    render: (row) => {
      const departments = row.matched_departments || [];
      if (departments.length === 0) return "-";
      return h(
        "div",
        { style: "display: flex; flex-wrap: wrap; gap: 4px" },
        departments.map((dept: string) =>
          h(ElTag, { type: "warning", size: "small" }, () => dept)
        )
      );
    },
  },
  {
    label: "匹配关键词",
    prop: "matched_keywords",
    minWidth: 200,
    show: true,
    render: (row) => {
      const keywords = row.matched_keywords || [];
      if (keywords.length === 0) return "-";
      return h(
        "div",
        { style: "display: flex; flex-wrap: wrap; gap: 4px" },
        keywords.map((keyword: string) =>
          h(ElTag, { type: "success", size: "small" }, () => keyword)
        )
      );
    },
  },
  {
    label: "评分",
    prop: "score",
    width: 100,
    show: true,
    render: (row) => {
      const score = row.score;
      if (score === undefined || score === null) return "-";
      return h(
        "span",
        {
          style: {
            color: getScoreColor(score),
            fontWeight: "600",
            fontSize: "14px",
          },
        },
        `${score}`
      );
    },
  },
  {
    label: "剩余时间",
    prop: "ttl_hours",
    width: 180,
    show: true,
    render: (row) => {
      const ttlHours = row.ttl_hours;
      const progress = getTTLProgress(ttlHours);
      const isExpiringSoon = ttlHours < 2;

      return h(
        "div",
        { style: "display: flex; flex-direction: column; gap: 4px" },
        [
          h("div", { style: "display: flex; align-items: center; gap: 8px" }, [
            h(
              "span",
              {
                style: isExpiringSoon ? "color: #f56c6c; font-weight: 500" : "",
              },
              formatTTL(ttlHours)
            ),
          ]),
          h("div", { style: "width: 100%" }, [
            h(
              "div",
              {
                style: {
                  width: "100%",
                  height: "6px",
                  backgroundColor: "#f0f0f0",
                  borderRadius: "3px",
                  overflow: "hidden",
                },
              },
              [
                h("div", {
                  style: {
                    width: `${progress}%`,
                    height: "100%",
                    backgroundColor: isExpiringSoon ? "#f56c6c" : "#67c23a",
                    transition: "width 0.3s",
                  },
                }),
              ]
            ),
          ]),
        ]
      );
    },
  },
  {
    label: "缓存时间",
    prop: "cached_at",
    width: 160,
    show: true,
  },
  {
    label: "操作",
    prop: "action",
    width: 180,
    show: true,
    slot: "cache_action",
    fixed: "right",
  },
]);

const fetchCacheList = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      per_page: pagination.pageSize,
    };

    if (filterForm.task_id) {
      params.task_id = filterForm.task_id;
    }

    if (filterForm.keyword?.trim()) {
      params.keyword = filterForm.keyword.trim();
    }

    const result = await getGithubCache(params);

    if (result.code === 2000 && result.data) {
      cacheList.value = result.data.items || [];
      pagination.total = result.data.total || 0;

      // 更新统计信息
      updateStatistics(result.data);
    } else {
      ElMessage.error(result.message || "获取缓存列表失败");
      cacheList.value = [];
      pagination.total = 0;
      statistics.value = [];
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取缓存列表失败");
    cacheList.value = [];
    pagination.total = 0;
    statistics.value = [];
  } finally {
    loading.value = false;
  }
};

// 更新统计信息
const updateStatistics = (data: any) => {
  const total = data.total || 0;
  // 计算即将过期（<2小时）的数量
  const expiringSoon = cacheList.value.filter(
    (item) => item.ttl_hours !== undefined && item.ttl_hours < 2
  ).length;

  statistics.value = [
    {
      label: "总缓存",
      value: total,
      bgColor: "#1890ff", // 蓝色
      span: 4, // 每行2个
    },
    {
      label: "即将过期(<2h)",
      value: expiringSoon,
      bgColor: expiringSoon > 0 ? "#f56c6c" : "#52c41a", // 有即将过期的显示红色，否则绿色
      span: 4, // 每行2个
    },
  ];
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchCacheList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchCacheList();
};

// 单个确认缓存
const handleConfirm = async (row: any) => {
  pendingConfirmKeys.value = [row.cache_key];
  showConfirmDialog.value = true;
};

// 批量确认缓存
const handleBatchConfirm = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要确认的缓存项");
    return;
  }
  pendingConfirmKeys.value = selectedRows.value.map((row) => row.cache_key);
  showConfirmDialog.value = true;
};

// 确认对话框确认回调
const handleConfirmSubmit = async (department: string, cacheKeys: string[]) => {
  try {
    loading.value = true;
    const result = await confirmGithubCache({
      cache_keys: cacheKeys,
      department: department,
    });

    const successCount = result.data?.success_count || cacheKeys.length;
    ElMessage.success(`成功确认 ${successCount} 个缓存项`);
    selectedRows.value = [];
    fetchCacheList();
  } catch (error: any) {
    ElMessage.error(error?.message || "确认失败");
  } finally {
    loading.value = false;
  }
};

// 单个忽略缓存
const handleIgnore = async (row: any) => {
  try {
    const fileName = row.path?.split("/").pop() || row.path || row.cache_key;
    await ElMessageBox.confirm(
      `确定要忽略缓存【${fileName}】吗？`,
      "忽略确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const result = await ignoreGithubCache({
      cache_keys: [row.cache_key],
    });

    if (result.code === 2000) {
      ElMessage.success("忽略成功");
      fetchCacheList();
    } else {
      ElMessage.error(result.message || "忽略失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "忽略失败");
    }
  }
};

// 批量忽略缓存
const handleBatchIgnore = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要忽略的缓存项");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要忽略选中的 ${selectedRows.value.length} 个缓存项吗？`,
      "批量忽略确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const cacheKeys = selectedRows.value.map((row) => row.cache_key);
    const result = await ignoreGithubCache({
      cache_keys: cacheKeys,
    });

    if (result.code === 2000) {
      const successCount = result.data?.success_count || cacheKeys.length;
      ElMessage.success(`成功忽略 ${successCount} 个缓存项`);
      selectedRows.value = [];
      fetchCacheList();
    } else {
      ElMessage.error(result.message || "忽略失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "忽略失败");
    }
  }
};

// 手动清理缓存
const handleCleanup = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要手动触发缓存清理吗？此操作会检查并清理过期的缓存项。",
      "清理确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const result = await cleanupGithubCache();

    if (result.code === 2000) {
      ElMessage.success("清理操作已提交");
      // 延迟刷新列表
      setTimeout(() => {
        fetchCacheList();
      }, 1000);
    } else {
      ElMessage.error(result.message || "清理失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "清理失败");
    }
  }
};

// 处理表格选择变化
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 搜索
const handleSearch = (formData: Record<string, any>) => {
  Object.assign(filterForm, formData);
  pagination.currentPage = 1;
  fetchCacheList();
};

// 重置筛选
const handleReset = () => {
  filterForm.task_id = "";
  filterForm.keyword = "";
  formRef.value?.resetFields();
  pagination.currentPage = 1;
  fetchCacheList();
};

onMounted(() => {
  fetchCacheList();
});

defineExpose({
  fetchCacheList,
});
</script>

<template>
  <div class="github-cache-management">
    <!-- 统计面板 -->
    <el-card style="margin-bottom: 20px" v-if="statistics.length > 0">
      <DynamicStatistics :items="statistics" />
    </el-card>

    <el-card style="margin-bottom: 20px">
      <DynamicForm
        :form-config="formConfig"
        :model-value="filterForm"
        type="search"
        ref="formRef"
        @search="handleSearch"
        @reset="handleReset"
      />
    </el-card>
    <el-card>
      <DynamicTable
        :pagination="pagination"
        :columns="historyColumns"
        :data="cacheList"
        :loading="loading"
        :showToolbar="true"
        selection-type="multiple"
        row-key="cache_key"
        @selection-change="handleSelectionChange"
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
        <template #toolbar-left>
          <el-button
            type="success"
            :disabled="selectedRows.length === 0"
            @click="handleBatchConfirm"
          >
            批量确认
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedRows.length === 0"
            @click="handleBatchIgnore"
          >
            批量忽略
          </el-button>
          <el-button type="warning" @click="handleCleanup">
            手动清理
          </el-button>
        </template>
        <template #cache_action="{ row }">
          <div class="action-buttons">
            <el-button
              type="success"
              size="small"
              @click="handleConfirm(row)"
              title="确认"
            >
              确认
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleIgnore(row)"
              title="忽略"
            >
              忽略
            </el-button>
          </div>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 确认对话框 -->
    <ConfirmCacheDialog
      v-model="showConfirmDialog"
      :cache-keys="pendingConfirmKeys"
      @confirm="handleConfirmSubmit"
    />
  </div>
</template>

<style scoped lang="scss">
.github-cache-management {
  padding: 20px;

  .action-buttons {
    display: flex;
    gap: 8px;
    align-items: center;
  }
}
</style>
